import datetime
import decimal
import json

from django.http import HttpResponse
from django.utils.translation import gettext
from rest_framework.pagination import LimitOffsetPagination, _positive_int
from rest_framework.response import Response as DRFResponse


class Response(DRFResponse):

    def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None,
                 msg="", extra=None):
        from django.utils.translation import gettext as _
        response_data = {
            "code": status,
            "msg": _(msg),
        }
        data = {} if data is None else data
        if isinstance(extra, dict):
            response_data.update(extra)
        if isinstance(data, dict):
            response_data["data"] = data
        else:
            response_data["data"] = {"detail": data}
        super(Response, self).__init__(data=response_data, status=200, template_name=template_name, headers=headers,
                                       exception=exception, content_type=content_type)

def returnResponse(res=None, status_code=200):
    if not res:
        res = {}

    # 补充国际化
    if isinstance(res, dict) and isinstance(res.get('msg'), str):
        res['msg'] = gettext(res['msg'])

    HttpResponse.status_code = status_code
    return HttpResponse(json.dumps(res, cls=Encoder), content_type="application/json")


class Encoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime("%Y-%m-%d")
        super(Encoder, self).default(o)

class PageSizePagination(LimitOffsetPagination):
    limit_query_param = 'page_size'
    offset_query_param = 'page'


    def get_offset(self, request):
        try:
            return (_positive_int(
                request.query_params[self.offset_query_param]
            ) - 1) * self.get_limit(request)
        except (KeyError, ValueError):
            return 0